import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/utils/url_utils.dart';
import 'stress_relief_logic.dart';

/// 减压冥想页面
class StressReliefView extends GetView<StressReliefLogic> {
  const StressReliefView({super.key});

  Widget _buildView() {
    return Obx(() {
      final selectedScene = controller.state.selectedScene.value;
      final backgroundImage = selectedScene?.relaxImage;

      return Container(
        decoration: BoxDecoration(
          image: backgroundImage != null
              ? DecorationImage(
                  image: NetworkImage(UrlUtils.toFullImageUrl(backgroundImage)),
                  fit: BoxFit.cover,
                  onError: (exception, stackTrace) {
                    print(
                        '背景图片加载失败: ${UrlUtils.toFullImageUrl(backgroundImage)}');
                  },
                )
              : null,
          gradient: backgroundImage == null
              ? LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: controller.getBackgroundGradient(),
                  stops: const [0.0, 0.7, 1.0],
                )
              : null,
        ),
        child: Container(
          // 添加深色遮罩
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.black.withOpacity(0.5),
                Colors.black.withOpacity(0.7),
                Colors.black.withOpacity(0.8),
              ],
              stops: const [0.0, 0.5, 1.0],
            ),
          ),
          child: SafeArea(
            child: Column(
              children: [
                _buildAppBar(),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildBreathingCircle(),
                      SizedBox(height: 40.h),
                      _buildBreathingGuide(),
                      SizedBox(height: 60.h),
                      _buildControlButtons(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget _buildAppBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.close,
                color: Colors.white,
                size: 24.sp,
              ),
            ),
          ),
          Text(
            '减压',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          GestureDetector(
            onTap: controller.showMenu,
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.menu,
                color: Colors.white,
                size: 24.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBreathingCircle() {
    return Obx(() => Container(
          width: 240.w,
          height: 240.h,
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 不规则圆形 - 始终显示
              if (controller.state.isActive.value)
                // 激活状态：大幅度呼吸动画
                AnimatedContainer(
                  duration: Duration(
                      milliseconds: controller.state.animationDuration.value),
                  curve: Curves.easeInOut,
                  width: controller.state.circleSize.value,
                  height: controller.state.circleSize.value,
                  child: CustomPaint(
                    painter: _IrregularCirclePainter(
                      color: Colors.white.withOpacity(0.3),
                      animationValue: controller.state.circleSize.value / 200.0,
                    ),
                  ),
                )
              else
                // 未激活状态：微波动圆形
                _IdleBreathingCircle(),

              // 时间选择或计时显示
              if (!controller.state.isActive.value)
                _buildTimeSelector()
              else
                _buildActiveTimer(),
            ],
          ),
        ));
  }

  Widget _buildTimeSelector() {
    return Obx(() {
      // 如果频次列表还未加载，显示加载状态
      if (controller.state.frequencies.isEmpty) {
        return SizedBox(
          height: 200.h,
          width: 120.w,
          child: const Center(
            child: CircularProgressIndicator(color: Colors.white),
          ),
        );
      }

      // 使用频次列表中的 minutes
      final availableMinutes = controller.state.frequencies
          .map((freq) => freq.minutes ?? 0)
          .where((min) => min > 0)
          .toList()
        ..sort(); // 排序

      if (availableMinutes.isEmpty) {
        return Container(
          height: 200.h,
          width: 120.w,
          child: Center(
            child: Text(
              '${controller.state.selectedMinutes.value}',
              style: TextStyle(
                fontSize: 48.sp,
                fontWeight: FontWeight.w300,
                color: Colors.white,
              ),
            ),
          ),
        );
      }

      return Container(
        height: 200.h,
        width: 120.w,
        child: Stack(
          children: [
            // 滚动时间选择器
            ListWheelScrollView(
              controller: controller.scrollController,
              itemExtent: 50.h,
              perspective: 0.005,
              diameterRatio: 1.2,
              physics: const FixedExtentScrollPhysics(),
              onSelectedItemChanged: (index) {
                if (index < availableMinutes.length) {
                  controller
                      .updateSelectedTimeByMinute(availableMinutes[index]);
                }
              },
              children: availableMinutes.map((minute) {
                return Obx(() {
                  final isSelected =
                      minute == controller.state.selectedMinutes.value;
                  return Container(
                    alignment: Alignment.center,
                    child: Text(
                      '$minute',
                      style: TextStyle(
                        fontSize: isSelected ? 48.sp : 28.sp,
                        fontWeight: FontWeight.w300,
                        color: isSelected
                            ? Colors.white
                            : Colors.white.withOpacity(0.5),
                      ),
                    ),
                  );
                });
              }).toList(),
            ),
            // 中心选中区域指示器
            Positioned.fill(
              child: Center(
                child: Container(
                  height: 50.h,
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                          color: Colors.white.withOpacity(0.2), width: 1),
                      bottom: BorderSide(
                          color: Colors.white.withOpacity(0.2), width: 1),
                    ),
                  ),
                ),
              ),
            ),
            // "分钟" 标签和呼吸次数
            Positioned(
              bottom: 0.h,
              left: 0,
              right: 0,
              child: Center(
                child: Column(
                  children: [
                    Text(
                      '分钟',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w300,
                        color: Colors.white.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget _buildActiveTimer() {
    return Obx(() => Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              controller.state.breathingInstruction.value,
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 16.h),
            
          ],
        ));
  }

  Widget _buildBreathingGuide() {
    return Obx(() => Column(
          children: [
            Text(
              controller.state.breathingInstruction.value,
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
            
          ],
        ));
  }

  Widget _buildControlButtons() {
    return Obx(() {
      final isActive = controller.state.isActive.value;
      final isPaused = controller.state.isPaused.value;
      
      return Column(
        children: [
          // 控制按钮
          if (!isActive)
            // 未开始：显示开始按钮
            GestureDetector(
              onTap: controller.startBreathing,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 16.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(30.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.play_arrow,
                      color: Colors.black87,
                      size: 24.sp,
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      '开始',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
            )
          else if (!isPaused)
            // 进行中：显示暂停按钮
            GestureDetector(
              onTap: controller.pauseBreathing,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 16.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(30.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.pause,
                      color: Colors.black87,
                      size: 24.sp,
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      '暂停',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
            )
          else
            // 暂停中：显示继续和结束按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: controller.resumeBreathing,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.h),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.9),
                      borderRadius: BorderRadius.circular(30.r),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.3),
                          blurRadius: 10,
                          offset: const Offset(0, 4),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.play_arrow,
                          color: Colors.black87,
                          size: 24.sp,
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          '继续',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.black87,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
                GestureDetector(
                  onTap: controller.stopBreathing,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.h),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(30.r),
                      border: Border.all(color: Colors.white.withOpacity(0.5), width: 1),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.stop,
                          color: Colors.white,
                          size: 24.sp,
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          '结束',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          // 场景音效按钮 - 只在未激活状态显示
          if (!isActive) ...[
            SizedBox(height: 32.h),
            GestureDetector(
              onTap: controller.showSceneSelector,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.all(16.w),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                      border: controller.state.isAmbientSoundOn.value
                          ? Border.all(color: Colors.orange, width: 2)
                          : null,
                    ),
                    child: Icon(
                      _getSceneIcon(),
                      color: Colors.orange,
                      size: 32.sp,
                    ),
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    controller.state.selectedScene.value?.relaxName ?? '场景',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white70,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      );
    });
  }

  /// 获取场景图标
  IconData _getSceneIcon() {
    final sceneName = controller.state.selectedScene.value?.relaxName;
    switch (sceneName) {
      case '烤火':
        return Icons.local_fire_department;
      case '溪流':
        return Icons.water;
      case '鸟鸣':
        return Icons.flutter_dash;
      case '海浪':
        return Icons.waves;
      case '雨滴':
        return Icons.water_drop;
      case '大风':
        return Icons.air;
      default:
        return Icons.music_note;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 初始化控制器
    Get.put(StressReliefLogic());

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: _buildView(),
    );
  }
}

/// 静止状态的微波动圆形
class _IdleBreathingCircle extends StatefulWidget {
  const _IdleBreathingCircle({Key? key}) : super(key: key);

  @override
  State<_IdleBreathingCircle> createState() => _IdleBreathingCircleState();
}

class _IdleBreathingCircleState extends State<_IdleBreathingCircle>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 3000),
      vsync: this,
    )..repeat(reverse: true);

    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return SizedBox(
          width: 200.w,
          height: 200.h,
          child: CustomPaint(
            painter: _IrregularCirclePainter(
              color: Colors.white.withOpacity(0.3),
              animationValue: 0.7 + _animation.value * 0.1, // 增加波动幅度
              timeOffset: _animation.value * 6.28, // 添加时间偏移让形状动态变化
            ),
          ),
        );
      },
    );
  }
}

/// 不规则圆形绘制器
class _IrregularCirclePainter extends CustomPainter {
  final Color color;
  final double animationValue;
  final double timeOffset;

  _IrregularCirclePainter({
    required this.color,
    required this.animationValue,
    this.timeOffset = 0.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    final center = Offset(size.width / 2, size.height / 2);
    final baseRadius = size.width / 2;

    // 创建不规则路径
    final path = Path();
    const segments = 60; // 增加分段数使圆更平滑

    for (int i = 0; i <= segments; i++) {
      final angle = (i / segments) * 2 * 3.14159;

      // 使用多个正弦波创建不规则效果，加入 timeOffset 让形状动态变化
      final irregularity = 0.05 *
          (1 + 0.3 * (animationValue - 0.7).abs()) * // 基础波动
          (sin(angle * 3 + animationValue * 2 + timeOffset) * 0.5 + // 第一层波动
              sin(angle * 5 - animationValue * 3 + timeOffset * 0.7) *
                  0.3 + // 第二层波动
              sin(angle * 7 + animationValue * 1.5 + timeOffset * 0.5) *
                  0.2); // 第三层波动

      final radius = baseRadius * (1 + irregularity);
      final x = center.dx + radius * cos(angle);
      final y = center.dy + radius * sin(angle);

      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }
    }

    path.close();
    canvas.drawPath(path, paint);

    // 添加内部填充效果
    final fillPaint = Paint()
      ..color = color.withOpacity(0.1)
      ..style = PaintingStyle.fill;
    canvas.drawPath(path, fillPaint);
  }

  @override
  bool shouldRepaint(_IrregularCirclePainter oldDelegate) {
    return oldDelegate.animationValue != animationValue ||
        oldDelegate.color != color ||
        oldDelegate.timeOffset != timeOffset;
  }
}

// 辅助函数
double sin(double value) => math.sin(value);
double cos(double value) => math.cos(value);
